package com.kehutong.wwin.service.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.kehutong.common.entity.Root;
import com.kehutong.wxapi.request.UserBatchDeleteRequest;
import com.kehutong.wxapi.request.UserCreateRequest;
import com.kehutong.wxapi.request.UserUpdateRequest;
import com.kehutong.wxapi.response.UserBatchDeleteResponse;
import com.kehutong.wxapi.response.UserCreateResponse;
import com.kehutong.wxapi.response.UserUpdateResponse;
import com.kehutong.wxapi.service.UserService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;

import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.Token;
import com.kehutong.wwin.service.entity.EmployeeMap;
import com.kehutong.wwin.service.util.WwInHttpClient;

@WebService("/wwin/employee/wwin")
public class ToWwinEmployeeService {

	@Inject
	private WwInHttpClient httpClient;
	@Inject
	private JdbcSession jdbcSession;

	@Inject
	private ToWwinDepartmentService wwinDepartmentService;

	@Inject
	private ToKhtDepartmentService khtDepartmentService;

	@Inject
	private UserService userService;

	@ReqMapping("/create")
	public Object createUser(Token token, JSONObject khtJson) throws Exception {
		EmployeeMap map = createEmployee(khtJson);
		UserCreateRequest userCreateRequest=new UserCreateRequest();
		userCreateRequest.setAccessToken(httpClient.getEmployeeAccessToken(token));
		userCreateRequest.setUserid(khtJson.getString("userid"));
		userCreateRequest.setName(map.getName());
		userCreateRequest.setAlias(khtJson.getString("alias"));
		userCreateRequest.setMobile(map.getMobile());
		userCreateRequest.setDepartment(map.getDepartments());
		userCreateRequest.setPosition(khtJson.getString("positionName"));
		userCreateRequest.setGender(map.getGender());
		userCreateRequest.setEmail(map.getEmail());
		userCreateRequest.setTelephone(khtJson.getString("telephone"));
		//todo 上级
		userCreateRequest.setEnable(1);
		userCreateRequest.setAddress(map.getAddress());
		userCreateRequest.setMainDepartment(map.getMainDepartment());
		UserCreateResponse userCreateResponse=userService.userCreate(userCreateRequest);
		if (userCreateResponse.getErrcode() != 0) {
			return Result.error(userCreateResponse.getErrcode(), userCreateResponse.getErrmsg());
		}

		String oldId=map.getKhtid();
/*
		JSONObject rs = httpClient.postWWin("/cgi-bin/department/create", token, true, http->{
			JSONObject json = map.toWwJson();
			http.setBody(json.toJSONString());
		});
		
		int result = rs.getIntValue("errcode");
		if (result != 0) {
			return Result.error(result, rs.getString("errmsg"));
		}
*/

		map.setId(map.getId());
		String newKhtId=ToKhtEmployeeService.toKhtId(token.getCompanyNo(),map.getId());
		map.setKhtid(newKhtId);

		JSONObject updateResult = httpClient.postKht("/basic/employee/service/updateIdByInner", token, http-> {
			http.addParam("oldId",oldId);
			http.addParam("newId",newKhtId);
		});
		jdbcSession.insert(map);
		return Result.success();
	}
	
	@ReqMapping("/update")
	public Object update(Token token, JSONObject khtJson) throws Exception {
		EmployeeMap map = getEmployee(khtJson);
		UserUpdateRequest userUpdateRequest=new UserUpdateRequest();
		userUpdateRequest.setAccessToken(httpClient.getEmployeeAccessToken(token));
		userUpdateRequest.setUserid(khtJson.getString("userid"));
		userUpdateRequest.setName(map.getName());
		userUpdateRequest.setAlias(khtJson.getString("alias"));
		userUpdateRequest.setMobile(map.getMobile());
		userUpdateRequest.setDepartment(map.getDepartments());
		userUpdateRequest.setPosition(khtJson.getString("positionName"));
		userUpdateRequest.setGender(map.getGender());
		userUpdateRequest.setEmail(map.getEmail());
		userUpdateRequest.setTelephone(khtJson.getString("telephone"));
		//todo 上级
		userUpdateRequest.setEnable(1);
		userUpdateRequest.setAddress(map.getAddress());
		userUpdateRequest.setMainDepartment(map.getMainDepartment());
		UserUpdateResponse userUpdateResponse=userService.userUpdate(userUpdateRequest);
		if (userUpdateResponse.getErrcode() != 0) {
			return Result.error(userUpdateResponse.getErrcode(), userUpdateResponse.getErrmsg());
		}
		return Result.success();
	}

	@ReqMapping("/delete")
	public Object delete(Token token, JSONObject khtJson) throws Exception {
		EmployeeMap map = getEmployee(khtJson);
		JSONObject rs = httpClient.postWWin("/cgi-bin/user/update", token, true, http->{
			http.addParam("userid", map.getId());
		});
		
		int result = rs.getIntValue("errcode");
		if (result != 0) {
			return Result.error(result, rs.getString("errmsg"));
		}

		jdbcSession.deleteById(map);
		return Result.success();
	}

	/**
	 * 批量删除微信员工
	 * @param token
	 * @param khtJson
	 * @return
	 * @throws Exception
	 */
	@ReqMapping("/batch/delete")
	public Object batchDelete(Token token, JSONObject khtJson) throws Exception {
		JSONArray ids=khtJson.getJSONArray("ids");
		List<EmployeeMap> deleteList = new ArrayList<>(ids.size());
		List<String> userIdList=new ArrayList<>();
		for (int i = 0; i < ids.size(); i ++) {
			EmployeeMap map = getEmployeeByKhtId(ids.getString(i));
			userIdList.add(map.getId());
			deleteList.add(map);
		}
		UserBatchDeleteRequest userBatchDeleteRequest=new UserBatchDeleteRequest();
		userBatchDeleteRequest.setAccessToken(httpClient.getEmployeeAccessToken(token));
		userBatchDeleteRequest.setUseridlist(userIdList);
		UserBatchDeleteResponse userBatchDeleteResponse=userService.userBatchDelete(userBatchDeleteRequest);
		if (userBatchDeleteResponse.getErrcode() != 0) {
			return Result.error(userBatchDeleteResponse.getErrcode(), userBatchDeleteResponse.getErrmsg());
		}
		jdbcSession.deleteById(deleteList);
		return Result.success();
	}


	
	@ReqMapping("/cgi-bin/user/batchdelete")
	public Object delete(Token token, JSONArray khtJsonArray) throws Exception {
		List<EmployeeMap> deleteList = new ArrayList<>(khtJsonArray.size());
		JSONObject rs = httpClient.postWWin("/cgi-bin/user/batchdelete", token, true, http->{
			JSONObject jsonObject = new JSONObject();
			JSONArray wwUserIds = new JSONArray(khtJsonArray.size());
			for (int i = 0; i < khtJsonArray.size(); i ++) {
				EmployeeMap map = getEmployeeByKhtId(khtJsonArray.getString(i));
				wwUserIds.add(map.getId());
				deleteList.add(map);
			}
			jsonObject.put("useridlist", wwUserIds);
			http.setBody(jsonObject.toJSONString());
		});
		
		int result = rs.getIntValue("errcode");
		if (result != 0) {
			return Result.error(result, rs.getString("errmsg"));
		}

		jdbcSession.deleteById(deleteList);
		return Result.success();
	}

	public JSONObject listEmployee(Token token) throws Exception {
		return httpClient.getWWin("/cgi-bin/user/list", token, true, http->{
			http.addParam("department_id", "1");
			http.addParam("fetch_child", "1");
		});
	}
	
	public EmployeeMap getEmployeeByKhtId(String khtId) {
		return jdbcSession.findOne(EmployeeMap.class)
					.eq("khtid", khtId)
					.exe();
	}

	private EmployeeMap createEmployee(JSONObject khtJson) {
		EmployeeMap item = Pool.newInstance(EmployeeMap.class);
		
		item.setId(khtJson.getString("userid"));
		item.setName(khtJson.getString("name"));
		JSONArray departmentsArray =wwinDepartmentService.toWwId(khtJson.getJSONArray("department"));
		item.setDepartments(JSONObject.parseArray(departmentsArray.toString(),Integer.class));
		Integer mainDepartment=1;
		if(item.getDepartments().size()>0){
			mainDepartment=item.getDepartments().get(0);
		}
		item.setMainDepartment(mainDepartment);
		item.setMobile(khtJson.getString("mobile"));
		item.setGender(khtJson.getString("gender"));
		item.setEmail(khtJson.getString("email"));
		item.setAvatar(khtJson.getString("avatar"));
		item.setAddress(khtJson.getString("address"));
		item.setKhtid(khtJson.getString("id"));
		
		return item;
	}
	
	private EmployeeMap getEmployee(JSONObject khtJson) {
		EmployeeMap item = getEmployeeByKhtId(khtJson.getString("id"));
		
		item.setName(khtJson.getString("name"));
		JSONArray departmentsArray =wwinDepartmentService.toWwId(khtJson.getJSONArray("department"));
		item.setDepartments(JSONObject.parseArray(departmentsArray.toString(),Integer.class));
		Integer mainDepartment=1;
		if(item.getDepartments().size()>0){
			mainDepartment=item.getDepartments().get(0);
		}
		item.setMainDepartment(mainDepartment);
		item.setMobile(khtJson.getString("mobile"));
		item.setGender(khtJson.getString("gender"));
		item.setEmail(khtJson.getString("email"));
		item.setAvatar(khtJson.getString("avatar"));
		item.setAddress(khtJson.getString("address"));
		item.setKhtid(khtJson.getString("id"));
		
		return item;
	}

	private JSONArray getDepartment(JSONObject wwJson) {
		JSONArray result = null;
		try {
			result = wwJson.getJSONArray("Department");
		} catch (Exception e) {
			String department = wwJson.getString("Department");
			if (department != null) {
				result = new JSONArray();
				String[] departments = department.split(",");
				result.addAll(Arrays.asList(departments));
			}
		}
		return result;
	}

}
